package cn.zyl.demo.common.beans;

import cn.zyl.demo.common.exception.BeansException;
import cn.zyl.demo.common.tools.StringTool;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * TreeNode类说明:树结构实体
 *
 * @author wsz
 * @version v1.0
 * @date 2020-07-24
 */
public class TreeNode<K extends CharSequence,V> implements Serializable {
    private static final long serialVersionUID = 1L;
    /** 节点id */
    private K id;
    /** 父节点id */
    private K pid;
    /** 节点名称 */
    private String name;
    /** 子节点集合 */
    private List<TreeNode<K,V>> childes;
    /** 节点数据 */
    private V data;

    public TreeNode(K id, String name) { this.id = id;this.name = name; }
    public TreeNode(K id, String name, V data) { this.id = id;this.name = name;this.data = data; }

    /** 节点id */
    public K getId() { return id; }
    /** 节点id */
    public void setId(K id) { this.id = id; }
    /** 父节点id */
    public K getPid() { return pid; }
    /** 父节点id */
    public void setPid(K pid) { this.pid = pid; }
    /** 节点名称 */
    public String getName() { return name; }
    /** 节点名称 */
    public void setName(String name) { this.name = name; }
    /** 子节点集合 */
    public List<TreeNode<K, V>> getChildes() { return childes; }
    /** 子节点集合 */
    public void setChildes(List<TreeNode<K, V>> childes) { this.childes = childes; }
    /** 节点数据 */
    public V getData() { return data; }
    /** 节点数据 */
    public void setData(V data) { this.data = data; }
    /** 添加子节点 */
    public void addChild(TreeNode<K, V> child){
        if(null == this.childes ){this.childes = new LinkedList<>();}
        BeansException.isNullThrow(child ,"[child] is null");
        BeansException.isTrueThrow( StringTool.isEmpty(child.getId()),"child.id is empty");
        BeansException.isTrueThrow(StringTool.isEmpty(child.getName()),"child.name is empty");
        child.setPid(this.id);
        this.childes.add(child);
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) { return true; }
        if (o == null || getClass() != o.getClass()) { return false; }
        TreeNode<?, ?> treeNode = (TreeNode<?, ?>) o;
        return id.equals(treeNode.id) && Objects.equals(pid, treeNode.pid) && name.equals(treeNode.name);
    }
    @Override
    public int hashCode() { return Objects.hash(id, pid, name); }
    @Override
    public String toString() {
        return "{" + "id=" + id + ", pid=" + pid + ", name='" + name + '\'' + ", childes=" + childes + ", data=" + data + '}';
    }
}
